<?php

namespace Library\Rabbitmq;

use \PhpAmqpLib\Exception\AMQPTimeoutException;

/**
 * rabbitmq 简单模型
 */
class Simple extends Msg
{
    protected $consumerAck;
    
    public function __construct($queue = '',$consumerAck = false)
    {
        //默认交换机队列rabbitmq
        if(!$queue){
            $this->queue = 'simple_queue';
        }else{
            $this->queue = $queue;
        }
        $this->consumerAck = $consumerAck;
        parent::__construct();
    }
    
    public function queue_set()
    {
        $this->channel->queue_declare($this->queue, false, false, false, false);
    }

    /**
     * 生产者 
     * 参数只有$content
     */
    public function publish($content, $exchange='', $routeKey='', $head = [])
    {
        return parent::publish($content, $exchange='', $this->queue, $head = []);
    }

    /**
     * 消费者
     */
    public function consumer($call_back,$consumerTag='')
    {
        try{
            if($this->consumerAck){
                $this->channel->basic_consume($this->queue, $consumerTag='', false, false, false, false, $call_back);
            }else{
                $this->channel->basic_consume($this->queue, $consumerTag='', false, true, false, false, $call_back); //不需要确认回复
            }
            while (count($this->channel->callbacks)) {
                $this->channel->wait();
            }
        }catch(AMQPTimeoutException $e){
            throw $e;
        }
        
    }
}